from PIL import Image
from StringIO import StringIO

def image_from_data(data):
    try:
        sio = StringIO(data)
        image = Image.open(sio)
    except Exception, e:
        raise Exception('Error loading image data, msg="%s"'%e.message)
    return image
    
def data_from_image(image, format = None):
    sio = StringIO()
    image.save(sio, format)
    return sio.getvalue()